package assignment1.delegation;

import java.util.ArrayList;
import java.util.Hashtable;

public class Class {

	public ArrayList<Class> prototypes; // list of prototypes
	public Hashtable<String, Function> dict; // function datastructure. should be private, but example is public
	public String name; // class name, used for testing superclass principle
	
	public Class(String nameInput) {
		this.prototypes = new ArrayList<Class>();
		this.dict = new Hashtable<String, Function>();
		this.name = nameInput;
	}
	
	// returns a new Class object, with current Class object as an entry in prototype list
	public Class extension(String nameInput) {
		Class subClass = new Class(nameInput);
		subClass.prototypes.add(this);// add current class to prototype list
		return subClass;
	}
	
	public Function searchFunc(String funcName) {
		if (this.dict.containsKey(funcName)) { // search in own class space
			System.out.println(funcName + " found in " + this.name);
			return this.dict.get(funcName);
		}
		System.out.println(funcName + " not found in " + this.name);
		for(int i = 0; i < prototypes.size(); i++) { // search the list of prototypes for the function (delegating)
			if (prototypes.get(i).dict.containsKey(funcName)) {
				System.out.println(funcName + " found in " + prototypes.get(i).name);
				return prototypes.get(i).dict.get(funcName);
			}
		}
		for(int i = 0; i < prototypes.size(); i++) { // recursively search the list of each prototype
			prototypes.get(i).searchFunc(funcName);
		}
		// if the recursive search would be executed before searching the whole list, the wrong function could be found
		return null;
	}
}
